package com.js.basehttp.common;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.js.basehttp.converter.GsonConverterFactory;
import com.js.basehttp.interceptor.HttpCacheInterceptor;
import com.js.basehttp.interceptor.HttpHeaderInterceptor;
import com.js.basehttp.interceptor.LoggingInterceptor;
import com.js.basicutils.Utils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * Created by zhpan on 2018/3/21.
 * https://github.com/zhpanvip/Retrofit2
 */

public class RetrofitUtils {

    private static OkHttpClient okHttpClient = null;
    private static Retrofit retrofit = null;

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            File cacheFile = new File(Utils.getApp().getCacheDir(), "cache");
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
            okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(Constants.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(Constants.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .addInterceptor(new LoggingInterceptor())
                    .addInterceptor(new HttpHeaderInterceptor())
                    .addNetworkInterceptor(new HttpCacheInterceptor())
                    // .sslSocketFactory(SslContextFactory.getSSLSocketFactoryForTwoWay())  // https认证 如果要使用https且为自定义证书 可以去掉这两行注释，并自行配制证书。
                    // .hostnameVerifier(new SafeHostnameVerifier())
                    .cache(cache)
                    .build();
        }
        return okHttpClient;
    }

    public static Retrofit getRetrofit(String baseUrl) {
        if (retrofit == null) {
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
            OkHttpClient okHttpClient = getOkHttpClient();
            retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(baseUrl)
                    .build();
        }
        return retrofit;
    }
}
